package com.googlecode.archimedes.util;

import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>
 * Takes an input String object and creates a Guid
 * for that object based on an MD5 hash algorithm.
 * </p>
 * 
 * <p>Created: Apr 8, 2005</p>
 * 
 * @author Erik Gustavson
 * @version $Id: GuidGenerator.java 267 2005-04-08 23:40:00 +0000 (Fri, 08 Apr 2005) erik $
 * 
 * @see http://www.javaexchange.com/aboutRandomGUID.html
 */
public class GuidGenerator {

    protected static Log        log    = LogFactory.getLog(GuidGenerator.class);

    /**
     * The algorithm to use for the digest.. for example, MD5
     */
    private static final String DIGEST = "MD5";

    /*
     * Method to generate the random GUID
     */
    public static String generate(final byte[] inputValue) throws Exception {

        MessageDigest digest = MessageDigest.getInstance(DIGEST);
        byte[] array = digest.digest(inputValue);

        StringBuilder raw = new StringBuilder(36);
        for (int j = 0; j < array.length; ++j) {
            int b = array[j] & 0xFF;
            if (b < 0x10) raw.append('0');
            raw.append(Integer.toHexString(b));
        }

        raw.insert(8, "-");
        raw.insert(13, "-");
        raw.insert(18, "-");
        raw.insert(23, "-");

        return raw.toString();
    }
}
